# +----------------------------------------------------------------------
# | ChatWork智能聊天办公系统
# +----------------------------------------------------------------------
# | 软件声明: 本系统并非自由软件,未经授权任何形式的商业使用均属非法。
# | 版权保护: 任何企业和个人不允许对程序代码以任何形式任何目的复制/分发。
# | 授权要求: 如有商业使用需求,请务必先与版权所有者取得联系并获得正式授权。
# +----------------------------------------------------------------------
# | Author: ChatWork Team <2474369941@qq.com>
# +----------------------------------------------------------------------
import xmltodict
from typing import Dict
from fastapi import APIRouter, Request
from fastapi.responses import Response
from weixin.client import WeixinMpAPI
from plugins.wechat.configs import WeChatConfig
from apps.api.service.weixin_service import WeixinService

router = APIRouter(prefix="/weixin", tags=["微信接口"])


@router.api_route("/reply", summary="微信公众号回调")
async def reply(request: Request):
    params = request.query_params
    config: Dict[str, str] = await WeChatConfig.get_oa_config()
    api = WeixinMpAPI(
        appid=config.get("app_id"),
        app_secret=config.get("app_secret"),
        mp_token=config.get("token"),
        signature=params.get("signature", ""),
        timestamp=params.get("timestamp", ""),
        echostr=params.get("echostr", ""),
        nonce=params.get("nonce", ""),
    )

    if request.method == "GET":
        content = "fail" if not api.validate_signature() else params.get("echostr", "")
        return Response(content=content, media_type="text/plain")
    else:
        if not api.validate_signature():
            return Response(content="fail", media_type="application/xml")

        xml_json = await request.body()
        xml_dict = xmltodict.parse(xml_json).get("xml")
        messages = await WeixinService.reply(xml_dict)
        return Response(content=messages, media_type="application/xml")
